#!/usr/bin/perl
#perl perl_create_illu_tcga.pl  -d ./ILLLUSC -a Human1M-Duov3_B.csv -t ILLLUSC
use Getopt::Std;
#use strict;
#getopt("d:a:e:t", \%args);
my %args;
getopt("a:d:t", \%args);
my $maindir = $args{d};
my $tpedfile =$args{t};
chomp($maindir);
chomp($tpedfile);
open(TPED,">$tpedfile.tped");
open(TFAM,">$tpedfile.tfam");

#opening each file in the directory
open(BUFF,"ls $maindir|");
###@maindirarr = split(/\//,$maindir);

my $line;
###$line = pop(@maindirarr);
###$maindir = join('/',@maindirarr);
my $nu = 1;
#$line = <BUFF>;
#asigning the alleles types according to the bird seed output file description
#print $line."\n";
my %mainhash;
my %flaghash;
#$line = <BUFF>;
while($line = <BUFF>)
{
        chomp($line);
	$BUFF = "BUFF$nu";
	open($BUFF,"$maindir/$line");
	my $liney;
	$liney = <$BUFF>;
	chomp($liney);
	#print $liney."\n";
	@arrey = split("\t",$liney);
	for($i=3;$i<@arrey;$i++)
	{
		$arrey[$i] =~ s/\t//g;
		$arrey[$i] =~ s/ //g;
		if($arrey[$i] ne "" && (!(exists($flaghash{$arrey[$i]}))))
		{
			$flaghash{$arrey[$i]} = $arrey[$i]; 
			print TFAM "$arrey[$i] $arrey[$i] 0 0 9 -9\n";
		}
	}
	$liney = <$BUFF>;
	while($liney=<$BUFF>)
	{
		chomp($liney);
		my @arr =split(/\t/,$liney);
			
			$arr[1] =~ s/X/23/g;
			$arr[1] =~ s/Y/24/g;
			$arr[1] =~ s/M/26/g;
			$arr[1] =~ s/XY/25/g;
			for($jy=3;$jy<@arr;$jy++)
			{
				$arr[$jy] =~ s/--/00/g;
				@genotype = split(//,$arr[$jy]);
				$genotype = join(" ",@genotype);	
				if($arr[1] ne "XY")
				{
					if(exists($mainhash{$arr[0]}))
					{
						$mainhash{$arr[0]} =$mainhash{$arr[0]}." ".$genotype;
					}
					else
					{
						$mainhash{$arr[0]} = $arr[1]." ".$arr[0]." "."0 ".$arr[2]." ".$genotype;
					}
				}
			}
		
	}
	$nu++;
	close($BUFF);	
}
#print tped file
while(my($key,$value) = each %mainhash)
{
	print TPED $value."\n";
}
